package com.ossjk.oa.advisory.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.Constant;
import com.ossjk.core.util.ExcelUtiles;
import com.ossjk.oa.advisory.entity.Customer;
import com.ossjk.oa.advisory.entity.Customerfw;
import com.ossjk.oa.advisory.entity.Discipline;
import com.ossjk.oa.advisory.entity.School;
import com.ossjk.oa.advisory.service.ICustomerService;
import com.ossjk.oa.advisory.service.ICustomerfwService;
import com.ossjk.oa.advisory.service.IDisciplineService;
import com.ossjk.oa.advisory.service.ISchoolService;
import com.ossjk.oa.advisory.vo.Customer51JobVo;
import com.ossjk.oa.advisory.vo.CustomerVo;
import com.ossjk.oa.advisory.vo.CustomerZhiLianVo;
import com.ossjk.oa.system.entity.Token;
import com.ossjk.oa.system.service.IEmployeeService;

/**
 * <p>
 * 学校对接人管理 前端控制器
 * </p>
 *
 * @author Jason
 * @since 2019-01-14
 */
@RestController
@RequestMapping("/advisory/customer")
public class CustomerController extends BaseController {
	@Autowired
	private ICustomerService iCustomerService;
	@Autowired
	private ICustomerfwService iCustomerfwService;
	@Autowired
	private ISchoolService iSchoolService;
	@Autowired
	private IDisciplineService iDisciplineService;

	@Autowired
	private IEmployeeService iEmployeeService;

	@RequiresPermissions("00150020")
	@GetMapping("/list")
	public Object list(String name, String sid, String did, String ectn, String period, String phone, String eid,
			String ottn, String elmt, String intt, String stime, String etime, String orderField, String orderDirection,
			Page page, HttpServletRequest request, HttpServletResponse response) {
		Wrapper wrapper = Condition.create().isWhere(true).ne("c.isdelete", 2);
		if (!CommonUtil.isBlank(name)) {
			wrapper.like("c.name", name);
		}
		if (!CommonUtil.isBlank(sid)) {
			wrapper.eq("c.sid", sid);
			if (!CommonUtil.isBlank(did)) {
				wrapper.eq("c.did", did);
			}
		}
		if (!CommonUtil.isBlank(ectn)) {
			wrapper.like("c.ectn", ectn);
		}
		if (!CommonUtil.isBlank(period)) {
			wrapper.like("c.period", period);
		}
		if (!CommonUtil.isBlank(phone)) {
			wrapper.like("c.phone", phone);
		}
		if (!CommonUtil.isBlank(eid)) {
			wrapper.like("c.eid", eid);
		}
		if (!CommonUtil.isBlank(ottn)) {
			wrapper.like("c.ottn", ottn);
		}
		if (!CommonUtil.isBlank(elmt)) {
			wrapper.like("c.elmt", elmt);
		}
		if (!CommonUtil.isBlank(intt)) {
			wrapper.like("c.intt", intt);
		}

		// 录入时间
		if (!CommonUtil.isBlank(stime)) {
			wrapper.ge("c.ettm", stime);
		}
		if (!CommonUtil.isBlank(etime)) {
			wrapper.le("c.ettm", CommonUtil.getLastSecondOfDay(CommonUtil.getDate(etime, "@ISO")));
		}

		// 字段排序
		if (!CommonUtil.isBlank(orderField)) {
			if (CommonUtil.isEquals(orderDirection, "asc")) {
				wrapper.orderBy(orderField, true);
			} else if (CommonUtil.isEquals(orderDirection, "desc")) {
				wrapper.orderBy(orderField, false);
			}
		}

		/*
		 * 跟进时间 if (!CommonUtil.isBlank(stime)) { wrapper.ge("cfw2.mtime", stime); } if
		 * (!CommonUtil.isBlank(etime)) { wrapper.le("cfw2.mtime", etime); }
		 */
		wrapper.orderBy("crtm", false).orderBy("cfw2.mtime", false);
		Token token = (Token) request.getAttribute(Constant.REQUEST_TOKEN_KEY);

		String expression = token.getExpression();
		Map map = JSON.parseObject(expression, Map.class);
		List<String> object = (List<String>) map.get("psub");
		page = iCustomerService.selectVoPage(page, wrapper, getCurrnetUserId(), object);
		return responseSuccess(page);
	}

	@RequiresPermissions("001500200020")
	@GetMapping("/getRecords")
	public Object getRecords(String cid, Page page) {
		Wrapper wrapper = Condition.create().isWhere(true).ne("ctf.isdelete", 2).orderBy("crtm");
		if (!CommonUtil.isBlank(cid)) {
			wrapper.eq("ctf.cid", cid);
		}
		page = iCustomerfwService.selectVoPage(page, wrapper);
		return responseSuccess(page);
	}

	@RequiresPermissions("001500200000")
	@PostMapping("/insert")
	public Object insert(Customer customer) {
		Wrapper wrapper = Condition.create().eq("phone", customer.getPhone());
		if (!CommonUtil.isBlank(iCustomerService.selectList(wrapper))) {
			return responseFail("客户手机号码已存在。。");
		}
		// 录入人
		customer.setEntry(getCurrnetUserId());
		// 录入时间
		customer.setEttm(CommonUtil.getDate());
		if (iCustomerService.insert(customer)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("001500200025")
	@GetMapping("/toInsertRecords/{id}")
	public Object toInsertRecords(@PathVariable("id") String id) {

		return responseSuccess(iCustomerService.selectById(id));
	}

	@RequiresPermissions("001500200025")
	@PostMapping("/insertRecords")
	public Object insertRecords(Customerfw customerfw, Date nftm) {
		customerfw.setEid(getCurrnetUserId());
		customerfw.setTime(new Date());
		if (iCustomerfwService.insert(customerfw, nftm)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("001500200030")
	@GetMapping("/toUpdate/{id}")
	public Object toUpdate(@PathVariable("id") String id) {
		Map map = new HashMap();
		Customer customer = iCustomerService.selectById(id);
		map.put("customer", customer);
		Discipline discipline = iDisciplineService.selectById(customer.getDid());
		return responseSuccess(map);
	}

	@RequiresPermissions("001500200030")
	@PutMapping("/update")
	public Object update(Customer customer, String[] areaIds) {
		if (iCustomerService.updateById(customer)) {
			return responseSuccess();
		} else {
			return responseFail();
		}

	}

	@RequiresPermissions("001500200005")
	@DeleteMapping("/delete/{id}")
	public Object delete(@PathVariable("id") String[] id, String reason) {
		System.out.println(reason);
		List list = new ArrayList();
		for (String string : id) {
			Customer customer = new Customer();
			customer.setId(string);
			customer.setReason(reason);
			list.add(customer);
		}
		iCustomerService.updateBatchById(list);
		if (iCustomerService.deleteBatchIds(Arrays.asList(id))) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("00150020")
	@GetMapping("/getDisciplineName/{id}")
	public Object getDisciplineName(@PathVariable("id") String id) {
		School school = iSchoolService.selectById(id);
		List list = null;
		if (!CommonUtil.isBlank(school)) {
			Wrapper wrapper = Condition.create().eq("sid", school.getId());
			list = iDisciplineService.selectList(wrapper);
		}
		return responseSuccess(list);
	}

	@RequiresPermissions("001500200035")
	@GetMapping("/toAssignment/{id}")
	public Object toAssignment(@PathVariable("id") String[] id) {
		return responseSuccess(id);
	}

	/**
	 * 分配跟进人
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("001500200035")
	@PutMapping("/assignment")
	public Object assignment(String[] cid, String[] lv, String[] eid) throws Exception {
		if (iCustomerService.batchUpdateAssignment(cid, lv, eid)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	/**
	 * 导出Excel
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/export")
	@RequiresPermissions("001500200040")
	public void export(String name, String sid, String did, String ectn, String period, String ottn, String elmt,
			String intt, String stime, String etime, ModelMap map, Page page, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().isWhere(true).ne("c.isdelete", 2);

		if (!CommonUtil.isBlank(name)) {
			wrapper.like("c.name", name);
		}
		if (!CommonUtil.isBlank(sid)) {
			wrapper.eq("c.sid", sid);
			if (!CommonUtil.isBlank(did)) {
				wrapper.eq("c.did", did);
			}
		}
		if (!CommonUtil.isBlank(ectn)) {
			wrapper.like("c.ectn", ectn);
		}
		if (!CommonUtil.isBlank(period)) {
			wrapper.like("c.period", period);
		}
		if (!CommonUtil.isBlank(ottn)) {
			wrapper.like("c.ottn", ottn);
		}
		if (!CommonUtil.isBlank(elmt)) {
			wrapper.like("c.elmt", elmt);
		}
		if (!CommonUtil.isBlank(intt)) {
			wrapper.like("c.intt", intt);
		}
		if (!CommonUtil.isBlank(stime)) {
			wrapper.ge("cfw2.mtime", stime);
		}
		if (!CommonUtil.isBlank(etime)) {
			wrapper.le("cfw2.mtime", etime);
		}

		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		Token token = (Token) request.getAttribute(Constant.REQUEST_TOKEN_KEY);

		String expression = token.getExpression();
		Map map2 = JSON.parseObject(expression, Map.class);
		List<String> object = (List<String>) map2.get("psub");
		List list = iCustomerService.selectVoPage(page, wrapper, getCurrnetUserId(), object).getRecords();
		ExcelUtiles.exportExcel(list, null, "客户信息", CustomerVo.class, "客户信息.xls", response);
	}

	@RequiresPermissions("001500200045")
	@PostMapping("/importExcel")
	public Object importExcel(MultipartFile file, String rstype) throws Exception {
		List list = null;
		// 51job
		if (CommonUtil.isEquals("1", rstype)) {
			List<Customer51JobVo> customerVos = ExcelUtiles.importExcel(file, 0, 1, Customer51JobVo.class);
			Workbook hssfWorkbook = ExcelUtiles.getWorkBook(file);

			for (Customer51JobVo customer51JobVo : customerVos) {
				for (Sheet sheet : hssfWorkbook) {
					if (sheet.getSheetName().indexOf(customer51JobVo.getName()) > -1) {
						// 读取自我评价
						Row zwpjrow = sheet.getRow(39);
						Cell zwpjcell = zwpjrow.getCell(2);
						customer51JobVo.setSelf(zwpjcell.getStringCellValue());
						// 读取项目经验
						String xmjyStr = "";
						for (int i = 40; i < sheet.getLastRowNum(); i++) {
							boolean isxmjy = false;
							Row row = sheet.getRow(i);
							for (Cell cell : row) {
								if (cell.getColumnIndex() == 1
										&& CommonUtil.isEquals("项目经验", cell.getStringCellValue())) {
									isxmjy = true;
								}
								if (isxmjy) {
									xmjyStr += cell.getStringCellValue() + "\r\n";
								}
							}
						}
						customer51JobVo.setExperience(xmjyStr);
					}
				}
			}
			list = iCustomerService.batchImportExcel(customerVos, rstype, getCurrnetUserId());
		} else
		// 智联
		if (CommonUtil.isEquals("2", rstype)) {
			List<CustomerZhiLianVo> customerVos = ExcelUtiles.importExcel(file, 0, 1, CustomerZhiLianVo.class);

			Workbook hssfWorkbook = ExcelUtiles.getWorkBook(file);

			for (CustomerZhiLianVo customerZhiLianVo : customerVos) {
				for (Sheet sheet : hssfWorkbook) {
					if (sheet.getSheetName().indexOf(customerZhiLianVo.getName()) > -1) {
						// 读取自我评价
						Row zwpjrow = sheet.getRow(22);
						Cell zwpjcell = zwpjrow.getCell(1);
						System.out.println(zwpjcell.getStringCellValue());
						customerZhiLianVo.setSelf(zwpjcell.getStringCellValue());
						// 读取项目经验
						String xmjyStr = "";
						boolean isxmjy = false;
						for (int i = 25; i < sheet.getLastRowNum(); i++) {
							Row row = sheet.getRow(i);
							for (Cell cell : row) {
								if (cell.getColumnIndex() == 0
										&& CommonUtil.isEquals("项目经验", cell.getStringCellValue())) {
									isxmjy = true;
								}
								if (cell.getColumnIndex() == 0
										&& CommonUtil.isEquals("教育经历", cell.getStringCellValue())) {
									isxmjy = false;
								}
								if (isxmjy) {
									xmjyStr += cell.getStringCellValue() + "\r\n";
								}
							}
						}
						System.out.println(xmjyStr);
						customerZhiLianVo.setExperience(xmjyStr);
					}
				}
			}

			list = iCustomerService.batchImportExcel(customerVos, rstype, getCurrnetUserId());
		} else
		// 自定义
		if (CommonUtil.isEquals("3", rstype)) {
			List<CustomerVo> customerVos = ExcelUtiles.importExcel(file, 0, 1, CustomerVo.class);
			list = iCustomerService.batchImportExcel(customerVos, rstype, getCurrnetUserId());

			// // excel数据
			// // List<CustomerVo> customerVos = ExcelUtiles.importExcel(file,
			// 0,
			// // 1, CustomerVo.class);
			// // 学校名称
			// Wrapper wrapper = Condition.create();// .ne("del", 2);
			// List<School> schools = iSchoolService.selectList(wrapper);
			// // 已存在数据
			// Wrapper wrapper3 = Condition.create();
			// List<Customer> customers = iCustomerService.selectList(wrapper3);
			// List list = new ArrayList();
			// for (Customer customer : customers) {
			// list.add(customer.getPhone());
			// }
			//
			// List exist = new ArrayList();
			// List<Customer> noExist = new ArrayList();
			//
			// for (CustomerVo customerVo : customerVos) {
			// if (list.contains(customerVo.getPhone())) {
			// // 已存在
			// if (!exist.contains(customerVo.getPhone())) {
			// exist.add(customerVo.getPhone());
			// }
			// } else {
			// // 不存在
			// Customer customer = new Customer();
			// customer.setDid(customerVo.getDid());
			// customer.setCid(customerVo.getCid());
			// customer.setEid(customerVo.getEid());
			// customer.setName(customerVo.getName());
			// customer.setPhone(customerVo.getPhone());
			// customer.setQq(customerVo.getQq());
			// customer.setWechat(customerVo.getWechat());
			// customer.setEctn(customerVo.getEctn());
			// customer.setPeriod(customerVo.getPeriod());
			// customer.setOttn(customerVo.getOttn());
			// customer.setElmt(customerVo.getElmt());
			// customer.setIntt(customerVo.getIntt());
			//
			// customer.setEntry(getCurrnetUserId());
			// customer.setEttm(CommonUtil.getDate());
			// for (School school : schools) {
			// if (school.getName().equals(customerVo.getSid())) {
			// customer.setSid(school.getId());
			// }
			// }
			// // if (isexist) {
			// // School school = new School();
			// // school.setName(customer.getSid());
			// // iSchoolService.insert(school);
			// // customer.setSid(school.getId());
			// // }
			// noExist.add(customer);
			// }
			// }
			// if (!noExist.isEmpty() && iCustomerService.insertBatch(noExist))
			// {
			// return responseSuccess(Constant.RESPONSE_MSG_SUCCESS,
			// JSON.toJSONString(exist));
			// } else {
			// return responseFail(Constant.RESPONSE_MSG_FAIL,
			// JSON.toJSONString(exist));
			// }
		}
		if (!CommonUtil.isBlank(list)) {
			return responseSuccess("批量导入成功，以下为已经存在的手机号码", JSON.toJSONString(list));
		} else {
			return responseSuccess();
		}

	}

	/**
	 * 预约面试时间
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("001500200050")
	@PutMapping("/updateInterviewTime")
	public Object updateInterviewTime(Customer customer) throws Exception {
		if (iCustomerService.updateById(customer)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("001500200055")
	@GetMapping("/listFollow")
	public Object listFollow(String name, String sid, String did, String ectn, String period, String ottn, String elmt,
			String intt, String stime, String etime, Page page, HttpServletRequest request,
			HttpServletResponse response) {
		Wrapper wrapper = Condition.create().isWhere(true).ne("c.isdelete", 2);
		if (!CommonUtil.isBlank(name)) {
			wrapper.like("c.name", name);
		}
		if (!CommonUtil.isBlank(sid)) {
			wrapper.eq("c.sid", sid);
			if (!CommonUtil.isBlank(did)) {
				wrapper.eq("c.did", did);
			}
		}
		if (!CommonUtil.isBlank(ectn)) {
			wrapper.like("c.ectn", ectn);
		}
		if (!CommonUtil.isBlank(period)) {
			wrapper.like("c.period", period);
		}
		if (!CommonUtil.isBlank(ottn)) {
			wrapper.like("c.ottn", ottn);
		}
		if (!CommonUtil.isBlank(elmt)) {
			wrapper.like("c.elmt", elmt);
		}
		if (!CommonUtil.isBlank(intt)) {
			wrapper.like("c.intt", intt);
		}
		if (!CommonUtil.isBlank(stime)) {
			wrapper.ge("cfw2.mtime", stime);
		}
		wrapper.andNew();
		wrapper.like("c.ivtm", CommonUtil.date());
		wrapper.or();
		wrapper.like("c.nftm", CommonUtil.date());
		wrapper.orderBy("c.ivtm", false).orderBy("crtm", false);
		wrapper.orderBy("cfw2.mtime", false).orderBy("crtm", false);
		Token token = (Token) request.getAttribute(Constant.REQUEST_TOKEN_KEY);

		String expression = token.getExpression();
		Map map = JSON.parseObject(expression, Map.class);
		List<String> object = (List<String>) map.get("psub");
		page = iCustomerService.selectVoPage(page, wrapper, getCurrnetUserId(), object);
		return responseSuccess(page);
	}

}
